import logging
import shutil
from datetime import datetime, timedelta
from pathlib import Path
import allure
import pytest
from tools.page import page_get

page_screenshot = None
@pytest.fixture(scope="session", autouse=True, name='page')
def page_param():
    global page_screenshot
    logging.info('开始启动浏览器')
    page_screenshot = page_get()
    yield page_screenshot
    page_screenshot.quit()
    logging.info('关闭浏览器')


# 实现异常截图
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    if rep.when == "call" and rep.failed:
        # allure.attach直接将截图二进制数据附加到allure报告中
        allure.attach(page_screenshot.get_screenshot(as_bytes='png', name='异常截图.png', full_page=True), "异常截图",
                      allure.attachment_type.PNG)


@pytest.fixture(scope="function", params=[['15867710780', 'yexiong1997']])
def login_聚水潭(request, page):
    logging.info('开始登录')
    page.get("https://www.erp321.com/login.aspx")
    page("#login_id").input(request.param[0])
    page("#password").input(request.param[1])
    page("#agreementCheck").click()
    page('立即登录').click()
    if page('注意：您的密码已经超过3个月未修改(304)，请您尽快修改密码！', timeout=3):
        page('确认').click()
    logging.info('登录成功')
    page.wait(5)


@pytest.fixture(scope="session", autouse=True, name='date_hour')
def date_hour_():
    date_hour = datetime.now().strftime('%H-%M-%S')
    yield date_hour


# 删除除今天和昨天外的其他数据
@pytest.fixture(scope="session", autouse=True)
def del_file(path='C:/揽收预警'):
    for elm in Path(path).glob('*'):
        today = datetime.now().strftime('%Y-%m-%d')
        yesterday = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
        if elm == Path(f'C:/揽收预警/{today}') or elm == Path(f'C:/揽收预警/{yesterday}'):
            continue
        elm.unlink() if elm.is_file() else shutil.rmtree(elm)
